package com.sciology.xpathutility.utils;

import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.formatter.ContentFormatter;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.formatter.IFormattingStrategy;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.ITokenScanner;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;

import com.sciology.xpathutility.view.XmlRuleScanner;
import com.sciology.xpathutility.view.XmlDocumentFormattingStrategy;

public class XMLSrcViewerConfiguration extends SourceViewerConfiguration {

	private XmlRuleScanner scanner;
	private IDocument requestDocument;
	private final Color DEFAULT_TAG_COLOR = new Color(Display.getCurrent(),
			new RGB(0, 0, 200));;

	public XMLSrcViewerConfiguration() {
		// TODO Auto-generated constructor stub
	}

	public XMLSrcViewerConfiguration(IDocument document) {
		requestDocument = document;
	}

	public IPresentationReconciler getPresentationReconciler(
			ISourceViewer sourceViewer) {
		PresentationReconciler reconciler = new PresentationReconciler();
		DefaultDamagerRepairer damager = new DefaultDamagerRepairer(
				getTagScanner());
		reconciler.setDamager(damager, IDocument.DEFAULT_CONTENT_TYPE);
		reconciler.setRepairer(damager, IDocument.DEFAULT_CONTENT_TYPE);
		return reconciler;
	}

	private ITokenScanner getTagScanner() {
		if (scanner == null) {
			scanner = new XmlRuleScanner();
			scanner.setDefaultReturnToken(new Token(new TextAttribute(
					DEFAULT_TAG_COLOR)));
		}
		return scanner;
	}

	public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
		ContentFormatter formatter = new ContentFormatter();
		IFormattingStrategy keyword = new XmlDocumentFormattingStrategy(
				requestDocument);
		formatter
				.setFormattingStrategy(keyword, IDocument.DEFAULT_CONTENT_TYPE);
		return formatter;
	}
}
